import { View, Text, Video, Image, Picker } from "@tarojs/components";
import { AtImagePicker, AtCheckbox, AtRadio, AtIcon } from "taro-ui";
import { useEffect, useState } from "react";
import "./index.scss";
import Taro, { useRouter } from "@tarojs/taro";
import {
  addStore,
  classifyList,
  getStoreDetail,
} from "@/services/entities/all";
import {
  back,
  getAddressArr,
  getAddressArrNew,
  getImageNumberByLevel,
  uploadFilesList,
} from "@/helper/utils";
import FormInput from "@/components/public/FormInput";
import FormTextarea from "@/components/public/FormTextarea";
import ico_list_map from "@/assets/image/ico_list_map.svg";
// import { AddressREG } from "@/constants/common";

const AddShopPage = () => {
  const router = useRouter();
  const { params } = router;
  const { type, id } = params;
  const [classType, setType] = useState<any>([]);
  const [imgNum, setImgNum] = useState(6);
  const [otherPhone, setOtherPhone] = useState<any>([]);
  const [otherAddress, setOtherAddress] = useState<any>([]);
  const [otherFactoryAddress, setOtherFactoryAddress] = useState<any>([]);
  const [form, setForm] = useState({
    name: "",
    userName: "",
    phone: "",
    landPhone: "",
    wxCode: "",
    levelTwo: "",
    contentDetail: "",
    businessType: [],
    address: "",
    addressNext: "",
    factoryAddress: "",
    addressPre: [],
    city: "",
    area: "",
    province: "",
    level: "",
    shopScope: "",
    contactCount: "",
    viewCount: "",
    imageUrl: [],
    operationImageUrl: [],
    operationVideoUrl: "",
  });

  const disabled = type === "3";

  const onChange = (key, value) => {
    if (disabled) {
      return;
    }
    const temp = { ...form };
    temp[key] = value;
    setForm(temp);
  };

  const chooseVideo = () => {
    if (disabled) {
      return;
    }
    Taro.chooseVideo({
      sourceType: ["album", "camera"],
      maxDuration: 60,
      camera: "back",
      success: function (res) {
        uploadFilesList([{ file: { path: res.tempFilePath } }]).then(
          (res2: any) => {
            console.log("222", res2);
            onChange("operationVideoUrl", res2[0].data);
          }
        );
      },
    });
  };

  const submit = () => {
    let addressArr = [];
    if (form.addressPre.length) {
      addressArr = getAddressArrNew(form.addressPre);
    }
    const result: any = {
      address: `${form.addressPre.join("")} ${form.addressNext}`,
      area: addressArr[2],
      city: addressArr[1],
      province: addressArr[0],
      contactCount: form.contactCount,
      contentDetail: form.contentDetail,
      enable: true,
      imageUrl: form.imageUrl.join(","),
      landPhone: form.landPhone,
      level: form.level ?? 1,
      levelTwo: form.levelTwo ?? 0,
      classifyList: form.businessType ?? [],
      name: form.name,
      operationImageUrl: form.operationImageUrl.join(","),
      operationVideoUrl: form.operationVideoUrl,
      phone: form.phone,
      shopScope: form.shopScope,
      userName: form.userName,
      viewCount: form.viewCount,
      wxUserId: "",
      wxCode: form.wxCode,
      factoryAddress: form.factoryAddress,
      phoneDetail: otherPhone.map((item) => item.phone).join(","),
      addressDetail: otherAddress.map((item) => item.address).join(","),
      otherFactoryAddress: otherFactoryAddress
        .map((item) => item.address)
        .join(","),
    };
    if (id) {
      result.id = id;
    }
    addStore(result).then(() => {
      back();
    });
  };

  const chooseImage = (key, value: any) => {
    if (disabled) {
      return;
    }
    uploadFilesList(value).then((res) => {
      onChange(
        key,
        res.map((item: any) => item.data)
      );
    });
  };

  useEffect(() => {
    if (id) {
      getStoreDetail({ id: id }).then((res: any) => {
        const addressArr = res.address?.split(" ") ?? [];
        setOtherPhone(
          res.phoneDetail
            ? res.phoneDetail.split(",").map((item) => {
                return { phone: item };
              })
            : []
        );
        setOtherAddress(
          res.addressDetail
            ? res.addressDetail.split(",").map((item) => {
                return { address: item };
              })
            : []
        );
        setOtherFactoryAddress(
          res.otherFactoryAddress
            ? res.otherFactoryAddress.split(",").map((item) => {
                return { address: item };
              })
            : []
        );
        setForm({
          name: res.name,
          contentDetail: res.contentDetail,
          city: res.city,
          area: res.area,
          province: res.province,
          userName: res.userName,
          phone: res.phone,
          landPhone: res.landPhone,
          wxCode: res.wxCode,
          businessType: res.classifyList ?? [],
          address: res.address,
          addressNext: addressArr[1],
          factoryAddress: res.factoryAddress,
          addressPre: getAddressArr(addressArr[0]),
          level: res.level ?? 1,
          levelTwo: res.levelTwo ?? 0,
          shopScope: res.shopScope,
          contactCount: res.contactCount,
          viewCount: res.viewCount,
          imageUrl: res.imageUrl ? res.imageUrl?.split(",") : [],
          operationImageUrl: res.operationImageUrl
            ? res.operationImageUrl?.split(",")
            : [],
          operationVideoUrl: res.operationVideoUrl,
        });
        setImgNum(getImageNumberByLevel(res?.level));
      });
    }
  }, [id]);

  useEffect(() => {
    classifyList({}).then((res: any) => {
      const result: any = [];
      res.forEach((item) => {
        item.list.forEach((child) => {
          result.push(child);
        });
      });
      setType(result);
    });

    if (type === "1") {
      Taro.setNavigationBarTitle({
        title: "新增商家",
      });
    }
    if (type === "2") {
      Taro.setNavigationBarTitle({
        title: "修改商家",
      });
    }
    if (type === "3") {
      Taro.setNavigationBarTitle({
        title: "商家详情",
      });
    }
  }, []);

  const chooseLocation = () => {
    Taro.chooseLocation({
      success: (res) => {
        console.log(res);
        onChange("address", res.address);
      },
    });
  };

  return (
    <View className="add-shop-container bg-page">
      <View className="flex-column">
        <Text className="mg-tb-24 ml-22 fs-24 lh-36 cl-A4A4A4">
          添加商家基本信息
        </Text>
        <FormInput
          value={form.name}
          disabled={disabled}
          label="商家名称"
          placeholder="请输入商家名称"
          onChange={(value) => {
            onChange("name", value);
          }}
        />
        <FormInput
          value={form.userName}
          label="联系人"
          placeholder="请输入联系人"
          disabled={disabled}
          onChange={(value) => {
            onChange("userName", value);
          }}
        />
        <FormInput
          value={form.contentDetail}
          label="活动信息"
          placeholder="请输入活动信息"
          disabled={disabled}
          onChange={(value) => {
            onChange("contentDetail", value);
          }}
        />
        <FormInput
          value={form.phone}
          label="手机号码"
          placeholder="请输入手机号码"
          disabled={disabled}
          type="number"
          onChange={(value) => {
            onChange("phone", value);
          }}
          right={
            <AtIcon
              value="add-circle"
              className="mr-12"
              size="24"
              color="#339933"
              onClick={() => {
                setOtherPhone((old) => [...old, { phone: "" }]);
              }}
            ></AtIcon>
          }
        />
        {otherPhone?.map((other, index) => {
          return (
            <FormInput
              key={index}
              value={other.phone}
              label="其它手机号"
              placeholder="请输入其它手机号"
              disabled={disabled}
              type="number"
              onChange={(value) => {
                const tmp = [...otherPhone];
                tmp[index].phone = value;
                setOtherPhone(tmp);
              }}
              right={
                <AtIcon
                  value="subtract-circle"
                  className="mr-12"
                  size="24"
                  color="#F00"
                  onClick={() => {
                    const tmp = [...otherPhone];
                    tmp.splice(index, 1);
                    setOtherPhone(tmp);
                  }}
                ></AtIcon>
              }
            />
          );
        })}
        <FormInput
          value={form.landPhone}
          label="座机号码"
          placeholder="请输入座机号码"
          onChange={(value) => {
            onChange("landPhone", value);
          }}
        />
        <FormInput
          value={form.wxCode}
          label="微信号"
          placeholder="请输入微信号"
          disabled={disabled}
          type="number"
          onChange={(value) => {
            onChange("wxCode", value);
          }}
        />
        <View className="line"></View>
        <FormTextarea
          value={form.shopScope}
          disabled={disabled}
          label="经营范围"
          placeholder="请输入经营范围"
          onChange={(value) => {
            onChange("shopScope", value);
          }}
        />
        {/* <View
          onClick={() => {
            chooseLocation();
          }}
          className="dis-flex align-center"
        >
          <View className="flex-1">
            <FormInput
              value={form.address}
              disabled={disabled}
              label="地址"
              placeholder="请输入地址"
            />
          </View>
          <View className="height-full dis-flex align-center bg-ffffff">
            <Image src={ico_list_map} className="img-32 ml-12" />
          </View>
        </View> */}
        <View className="dis-flex pd-lr-26 border-box bg-ffffff">
          <View className="flex-1 fs-26 lh-32 cl-848484 pd-tb-24 border-box">
            所在地区：
          </View>
          <View
            className="border-bottom flex-3 fs-26 lh-32 cl-black pd-tb-24 border-box dis-flex align-center justify-between"
            // onClick={chooseLocation}
          >
            <Picker
              mode="region"
              value={form.addressPre}
              onChange={(e) => {
                onChange("addressPre", e.detail.value);
              }}
            >
              <View className="dis-flex align-center city">
                <Text className="fs-28 lh-38 cl-black">
                  {form.addressPre?.length
                    ? form.addressPre.join("")
                    : "选择省市区"}
                </Text>
              </View>
            </Picker>
            <Image src={ico_list_map} className="img-32" />
          </View>
        </View>
        {/* <View className="dis-flex pd-lr-26 border-box bg-ffffff">
          <View className="flex-1 fs-26 lh-32 cl-848484 pd-tb-24 border-box">
          详细地址：
          </View>
          <View
            className="border-bottom flex-3 fs-26 lh-32 cl-black pd-tb-24 border-box dis-flex align-center justify-between"
            onClick={chooseLocation}
          >
            <Image src={ico_list_map} className="img-32" />
          </View>
        </View> */}
        <FormInput
          value={form.addressNext}
          label="详细地址"
          placeholder="请输入详细地址"
          onChange={(value) => {
            onChange("addressNext", value);
          }}
          right={
            <AtIcon
              value="add-circle"
              className="mr-12"
              size="24"
              color="#339933"
              onClick={() => {
                setOtherAddress((old) => [...old, { address: "" }]);
              }}
            ></AtIcon>
          }
        />
        {otherAddress?.map((_, index) => {
          return (
            <FormInput
              key={index}
              value={otherAddress[index].address}
              label="其它店铺地址"
              placeholder="请输入其它店铺地址"
              disabled={disabled}
              type="number"
              onChange={(value) => {
                const tmp = [...otherAddress];
                tmp[index].address = value;
                setOtherAddress(tmp);
              }}
              right={
                <AtIcon
                  value="subtract-circle"
                  className="mr-12"
                  size="24"
                  color="#F00"
                  onClick={() => {
                    const tmp = [...otherAddress];
                    tmp.splice(index, 1);
                    setOtherAddress(tmp);
                  }}
                ></AtIcon>
              }
            />
          );
        })}
        <FormInput
          value={form.factoryAddress}
          label="厂家地址"
          placeholder="请输入厂家地址"
          onChange={(value) => {
            onChange("factoryAddress", value);
          }}
          right={
            <AtIcon
              value="add-circle"
              className="mr-12"
              size="24"
              color="#339933"
              onClick={() => {
                setOtherFactoryAddress((old) => [...old, { address: "" }]);
              }}
            ></AtIcon>
          }
        />
        {otherFactoryAddress?.map((_, index) => {
          return (
            <FormInput
              key={index}
              value={otherFactoryAddress[index].address}
              label="其它厂家地址"
              placeholder="请输入厂家地址"
              disabled={disabled}
              type="number"
              onChange={(value) => {
                const tmp = [...otherFactoryAddress];
                tmp[index].address = value;
                setOtherFactoryAddress(tmp);
              }}
              right={
                <AtIcon
                  value="subtract-circle"
                  className="mr-12"
                  size="24"
                  color="#F00"
                  onClick={() => {
                    const tmp = [...otherFactoryAddress];
                    tmp.splice(index, 1);
                    setOtherFactoryAddress(tmp);
                  }}
                ></AtIcon>
              }
            />
          );
        })}
        <FormInput
          value={form.viewCount}
          disabled={disabled}
          label="浏览次数"
          placeholder="请输入浏览次数"
          onChange={(value) => {
            onChange("viewCount", value);
          }}
        />
        <FormInput
          value={form.contactCount}
          label="联系次数"
          disabled={disabled}
          placeholder="请输入联系次数"
          onChange={(value) => {
            onChange("contactCount", value);
          }}
        />
        <View className="line"></View>
        <View className="flex-column bg-ffffff">
          <Text className="mg-tb-24 ml-22 fs-24 lh-36 cl-A4A4A4">商家类型</Text>
        </View>
        <View className="flex-column pd-lr-24 pd-tb-28 border-box bg-ffffff">
          <AtCheckbox
            options={classType?.map((item) => {
              return {
                value: item.id,
                label: item.name,
              };
            })}
            selectedList={form.businessType}
            onChange={(value) => {
              console.log("value", value);
              onChange("businessType", value);
            }}
          />
        </View>
        <View className="flex-column bg-ffffff">
          <Text className="mg-tb-24 ml-22 fs-24 lh-36 cl-A4A4A4">商家等级</Text>
        </View>
        <View className="flex-column pd-lr-24 pd-tb-28 border-box bg-ffffff">
          <AtRadio
            options={[
              { label: "优质商家", value: 4 },
              { label: "荣誉商家", value: 3 },
              { label: "普通商家", value: 2 },
              { label: "二级商家", value: 1 },
            ]}
            value={form.level}
            onClick={(value) => {
              onChange("level", value);
            }}
          />
        </View>
        {parseInt(form.level) === 4 && (
          <FormInput
            value={form.levelTwo}
            label="优质等级"
            type="number"
            disabled={disabled}
            placeholder="请输入优质等级"
            onChange={(value) => {
              onChange("levelTwo", value);
            }}
          />
        )}
        <Text className="mg-tb-24 ml-22 fs-24 lh-36 cl-A4A4A4">
          添加图片&视频信息
        </Text>
        <View className="flex-column pl-4 pr-24 pd-tb-28 border-box bg-ffffff">
          <Text className="mb-28 pl-20 border-box fs-28 lh-36 cl-848484">
            上传商家banner图片
          </Text>
          <AtImagePicker
            files={form.imageUrl?.map((item) => {
              return { url: item };
            })}
            count={9}
            multiple={true}
            onChange={(files) => {
              chooseImage("imageUrl", files);
            }}
          ></AtImagePicker>
          <Text className="mg-tb-28 pl-20 border-box fs-28 lh-36 cl-848484">
            上传商家经营图片
          </Text>
          <AtImagePicker
            files={form.operationImageUrl?.map((item) => {
              return { url: item };
            })}
            count={imgNum}
            multiple={true}
            onChange={(files) => {
              chooseImage("operationImageUrl", files);
            }}
          ></AtImagePicker>
          <Text className="mg-tb-28 pl-20 border-box fs-28 lh-36 cl-848484">
            上传商家经营视频
          </Text>
          <View class="dis-flex">
            <View
              className="upload ml-20 fs-40 flex-center mb-80"
              onClick={chooseVideo}
            >
              {form.operationVideoUrl ? (
                <Video className="video" src={form.operationVideoUrl}></Video>
              ) : (
                <View className="add">
                  <View className="add-bar"></View>
                  <View className="add-bar-line"></View>
                </View>
              )}
            </View>
            {form.operationVideoUrl && (
              <Text
                className="cl-E14848 fs-32 ml-12"
                onClick={() => {
                  onChange("operationVideoUrl", "");
                }}
              >
                删除
              </Text>
            )}
          </View>
        </View>
      </View>
      {!disabled && (
        <View className="bottom pd-20  dis-flex align-center border-box">
          <View
            className="flex-1 flex-center pd-tb-20 border-box bg-ffffff br-8 fs-28 lh-38 cl-848484"
            onClick={() => {
              back();
            }}
          >
            取消
          </View>
          <View className="empty"></View>
          <View
            className="flex-1 flex-center pd-tb-20 border-box bg-007DDB br-8 fs-28 lh-38 cl-white"
            onClick={submit}
          >
            提交
          </View>
        </View>
      )}
    </View>
  );
};

export default AddShopPage;
